package com.imc.platform.base.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.imc.api.order.pojo.UserOrgAccount;
import com.imc.core.utils.ClearTempImg;
import com.imc.core.utils.MenuUtils;
import com.imc.core.utils.MysqlUtil;
import com.imc.core.utils.UploadUtiles;
import com.imc.platform.base.org.pojo.Org;
import com.imc.platform.base.org.pojo.OrgZTreeNode;
import com.imc.platform.base.org.service.IOrgService;
import com.imc.platform.base.user.dao.mapper.IUserMapper;
import com.imc.platform.base.user.pojo.*;
import com.imc.platform.base.user.service.IUserService;
import com.twp.common.component.process.exception.combo.IComboExecptionForTFunc;
import com.twp.common.tuple.ResultDTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 类描述：用户管理
 * 开发者：QY
 * 创建时间：2018/9/3 8:00
 **/
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    public static final String imgUrl = "/images/user/";
    @Autowired
    IUserService userService;
    @Autowired
    ClearTempImg clearTempImg;
    @Autowired
    IOrgService orgService;
    @Autowired
    private IUserMapper userMapper;

    @Autowired
    MenuUtils menuUtils;

    @Autowired
    IComboExecptionForTFunc iComboExecptionForTFunc;

    @Autowired
    UploadUtiles uploadUtiles;

    @Autowired
    MysqlUtil mysqlUtil;

    /**
     * QY 2018/9/3 8:01
     * 方法描述：传参对象
     **/
    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    public static class ReqTuple {
        Map <String, Object> parmsMap;
        List <Map <String, Object>> parmsList;
        String userId;
        User  user;
    }

    /**
     * QY 2018/9/3 8:32
     * 方法描述：跳转用户页面
     **/
    @RequestMapping(value = "/showUserPage", method = RequestMethod.GET)
    public String showUserPage(String menuId, Model model, HttpServletRequest request,String type,String stype) {
        model.addAttribute("menu", menuUtils.getMenuByRoleId(request, menuId));
        model.addAttribute("menuId",menuId);
        model.addAttribute("type", stype);//学生管理
        model.addAttribute("stype", stype);//校长管理
        return "base/user/user";
    }


    /**
     * QY 2018/9/3 8:32
     * 方法描述：跳转新增用户页
     **/
    @RequestMapping(value = "/showUserAddPage", method = RequestMethod.GET)
    public String showUserAddPage(Principal principal,@RequestParam String menuId, @RequestParam String type, Model model) {
        String uname = principal.getName();
        model.addAttribute("menuId",menuId);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        User user = mysqlUtil.getUserByLoginNameCommon(uname);
        model.addAttribute("stype", type);//当前点击的菜单类型
        if ("admin".equals(user.getDuty())) {
            model.addAttribute("type", "0");
        }
        else if ("master".equals(user.getDuty())) {
            model.addAttribute("type", "1");
        } else if ("branch".equals(user.getDuty())) {
            model.addAttribute("type", "2");
        } else if ("teacher".equals(user.getDuty())) {
            model.addAttribute("type", "3");
        } else {
            model.addAttribute("type", "4");
        }
        return "base/user/addUser";
    }

    /**
     * QY 2018/9/4 23:49
     * 方法描述：跳转查看页面
     **/
    @RequestMapping(value = "/showSUserPage", method = RequestMethod.GET)
    public String showSUserPage(Principal principal,@RequestParam String menuId, @RequestParam String type,@RequestParam String userId, Model model, HttpServletRequest request) {
        model.addAttribute("userId", userId);
        model.addAttribute("menuId",menuId);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        model.addAttribute("menuSub", menuUtils.getMenuByRoleId(request, "21"));
        User userCurrent = userService.queryUserById(userId);
        if ("master".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "1");
        } else if ("branch".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "2");
        } else if ("teacher".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "3");
        } else {
            model.addAttribute("ctype", "4");
        }
        String uname = principal.getName();
        User user = mysqlUtil.getUserByLoginNameCommon(uname);
        model.addAttribute("stype", type);//当前点击的菜单类型
        if ("admin".equals(user.getDuty())) {
            model.addAttribute("type", "0");
        }else if ("master".equals(user.getDuty())) {
            model.addAttribute("type", "1");
        } else if ("branch".equals(user.getDuty())) {
            model.addAttribute("type", "2");
        } else if ("teacher".equals(user.getDuty())) {
            model.addAttribute("type", "3");
        } else {
            model.addAttribute("type", "4");
        }
        return "base/user/showUser";
    }

    /**
     * QY 2018/9/3 16:13
     * 方法描述：跳转到修改页面
     **/
    @RequestMapping(value = "/showUpdateUserPage", method = RequestMethod.GET)
    public String showUpdateUserPage(Principal principal,@RequestParam String menuId, @RequestParam String type, @RequestParam String userId, Model model, HttpServletRequest request) {
        model.addAttribute("userId", userId);
        model.addAttribute("menuId",menuId);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        model.addAttribute("menuSub", menuUtils.getMenuByRoleId(request, "22"));
        model.addAttribute("userId", userId);
        User userCurrent = userService.queryUserById(userId);
        if ("master".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "1");
        } else if ("branch".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "2");
        } else if ("teacher".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "3");
        } else {
            model.addAttribute("ctype", "4");
        }
        String uname = principal.getName();
        User user = mysqlUtil.getUserByLoginNameCommon(uname);
        model.addAttribute("stype", type);//当前点击的菜单类型
        if ("admin".equals(user.getDuty())) {
            model.addAttribute("type", "0");
        }else if ("master".equals(user.getDuty())) {
            model.addAttribute("type", "1");
        } else if ("branch".equals(user.getDuty())) {
            model.addAttribute("type", "2");
        } else if ("teacher".equals(user.getDuty())) {
            model.addAttribute("type", "3");
        } else {
            model.addAttribute("type", "4");
        }
        return "base/user/updateUser";
    }

    /**
     * QY 2018/9/3 8:32
     * 方法描述：跳转新增用户页
     **/
    @RequestMapping(value = "/showTeacherAddPage", method = RequestMethod.GET)
    public String showTeacherAddPage(Principal principal,@RequestParam String menuId, @RequestParam String type, Model model) {
        String uname = principal.getName();
        model.addAttribute("menuId",menuId);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        User user = mysqlUtil.getUserByLoginNameCommon(uname);
        model.addAttribute("stype", type);//当前点击的菜单类型
        if ("admin".equals(user.getDuty())) {
            model.addAttribute("type", "0");
        }
        else if ("master".equals(user.getDuty())) {
            model.addAttribute("type", "1");
        } else if ("branch".equals(user.getDuty())) {
            model.addAttribute("type", "2");
        } else if ("teacher".equals(user.getDuty())) {
            model.addAttribute("type", "3");
        } else {
            model.addAttribute("type", "4");
        }
        return "base/user/addUser";
    }

    /**
     * QY 2018/9/4 23:49
     * 方法描述：跳转查看页面
     **/
    @RequestMapping(value = "/showSTeacherPage", method = RequestMethod.GET)
    public String showSTeacherPage(Principal principal,@RequestParam String menuId, @RequestParam String type,@RequestParam String userId, Model model, HttpServletRequest request) {
        model.addAttribute("userId", userId);
        model.addAttribute("menuId",menuId);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        model.addAttribute("menuSub", menuUtils.getMenuByRoleId(request, "21"));
        User userCurrent = userService.queryUserById(userId);
        if ("master".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "1");
        } else if ("branch".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "2");
        } else if ("teacher".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "3");
        } else {
            model.addAttribute("ctype", "4");
        }
        String uname = principal.getName();
        User user = mysqlUtil.getUserByLoginNameCommon(uname);
        model.addAttribute("stype", type);//当前点击的菜单类型
        if ("admin".equals(user.getDuty())) {
            model.addAttribute("type", "0");
        }else if ("master".equals(user.getDuty())) {
            model.addAttribute("type", "1");
        } else if ("branch".equals(user.getDuty())) {
            model.addAttribute("type", "2");
        } else if ("teacher".equals(user.getDuty())) {
            model.addAttribute("type", "3");
        } else {
            model.addAttribute("type", "4");
        }
        return "base/user/showUser";
    }

    /**
     * QY 2018/9/3 16:13
     * 方法描述：跳转到修改页面
     **/
    @RequestMapping(value = "/showUpdateTeacherPage", method = RequestMethod.GET)
    public String showUpdateTeacherPage(Principal principal,@RequestParam String menuId, @RequestParam String type, @RequestParam String userId, Model model, HttpServletRequest request) {
        model.addAttribute("userId", userId);
        model.addAttribute("menuId",menuId);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        model.addAttribute("menuSub", menuUtils.getMenuByRoleId(request, "22"));
        model.addAttribute("userId", userId);
        User userCurrent = userService.queryUserById(userId);
        if ("master".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "1");
        } else if ("branch".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "2");
        } else if ("teacher".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "3");
        } else {
            model.addAttribute("ctype", "4");
        }
        String uname = principal.getName();
        User user = mysqlUtil.getUserByLoginNameCommon(uname);
        model.addAttribute("stype", type);//当前点击的菜单类型
        if ("admin".equals(user.getDuty())) {
            model.addAttribute("type", "0");
        }else if ("master".equals(user.getDuty())) {
            model.addAttribute("type", "1");
        } else if ("branch".equals(user.getDuty())) {
            model.addAttribute("type", "2");
        } else if ("teacher".equals(user.getDuty())) {
            model.addAttribute("type", "3");
        } else {
            model.addAttribute("type", "4");
        }
        return "base/user/updateUser";
    }

    /**
     * QY 2018/9/3 8:32
     * 方法描述：跳转新增用户页
     **/
    @RequestMapping(value = "/showStudentAddPage", method = RequestMethod.GET)
    public String showStudentAddPage(Principal principal,@RequestParam String menuId, @RequestParam String type, Model model) {
        String uname = principal.getName();
        model.addAttribute("menuId",menuId);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        User user = mysqlUtil.getUserByLoginNameCommon(uname);
        model.addAttribute("stype", type);//当前点击的菜单类型
        if ("admin".equals(user.getDuty())) {
            model.addAttribute("type", "0");
        }
        else if ("master".equals(user.getDuty())) {
            model.addAttribute("type", "1");
        } else if ("branch".equals(user.getDuty())) {
            model.addAttribute("type", "2");
        } else if ("teacher".equals(user.getDuty())) {
            model.addAttribute("type", "3");
        } else {
            model.addAttribute("type", "4");
        }
        return "base/user/addUser";
    }

    /**
     * QY 2018/9/4 23:49
     * 方法描述：跳转查看页面
     **/
    @RequestMapping(value = "/showSStudentPage", method = RequestMethod.GET)
    public String showSStudentPage(Principal principal,@RequestParam String menuId, @RequestParam String type,@RequestParam String userId, Model model, HttpServletRequest request) {
        model.addAttribute("userId", userId);
        model.addAttribute("menuId",menuId);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        model.addAttribute("menuSub", menuUtils.getMenuByRoleId(request, "21"));
        User userCurrent = userService.queryUserById(userId);
        if ("master".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "1");
        } else if ("branch".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "2");
        } else if ("teacher".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "3");
        } else {
            model.addAttribute("ctype", "4");
        }
        String uname = principal.getName();
        User user = mysqlUtil.getUserByLoginNameCommon(uname);
        model.addAttribute("stype", type);//当前点击的菜单类型
        if ("admin".equals(user.getDuty())) {
            model.addAttribute("type", "0");
        }else if ("master".equals(user.getDuty())) {
            model.addAttribute("type", "1");
        } else if ("branch".equals(user.getDuty())) {
            model.addAttribute("type", "2");
        } else if ("teacher".equals(user.getDuty())) {
            model.addAttribute("type", "3");
        } else {
            model.addAttribute("type", "4");
        }
        return "base/user/showUser";
    }

    /**
     * QY 2018/9/3 16:13
     * 方法描述：跳转到修改页面
     **/
    @RequestMapping(value = "/showUpdateStudentPage", method = RequestMethod.GET)
    public String showUpdateStudentPage(Principal principal,@RequestParam String menuId, @RequestParam String type, @RequestParam String userId, Model model, HttpServletRequest request) {
        model.addAttribute("userId", userId);
        model.addAttribute("menuId",menuId);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        model.addAttribute("menuSub", menuUtils.getMenuByRoleId(request, "22"));
        model.addAttribute("userId", userId);
        User userCurrent = userService.queryUserById(userId);
        if ("master".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "1");
        } else if ("branch".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "2");
        } else if ("teacher".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "3");
        } else {
            model.addAttribute("ctype", "4");
        }
        String uname = principal.getName();
        User user = mysqlUtil.getUserByLoginNameCommon(uname);
        model.addAttribute("stype", type);//当前点击的菜单类型
        if ("admin".equals(user.getDuty())) {
            model.addAttribute("type", "0");
        }else if ("master".equals(user.getDuty())) {
            model.addAttribute("type", "1");
        } else if ("branch".equals(user.getDuty())) {
            model.addAttribute("type", "2");
        } else if ("teacher".equals(user.getDuty())) {
            model.addAttribute("type", "3");
        } else {
            model.addAttribute("type", "4");
        }
        return "base/user/updateUser";
    }

    /**
     * QY 2018/9/3 8:32
     * 方法描述：跳转新增用户页
     **/
    @RequestMapping(value = "/showMasterAddPage", method = RequestMethod.GET)
    public String showMasterAddPage(Principal principal,@RequestParam String menuId, @RequestParam String type, Model model) {
        String uname = principal.getName();
        model.addAttribute("menuId",menuId);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        User user = mysqlUtil.getUserByLoginNameCommon(uname);
        model.addAttribute("stype", type);//当前点击的菜单类型
        if ("admin".equals(user.getDuty())) {
            model.addAttribute("type", "0");
        }
        else if ("master".equals(user.getDuty())) {
            model.addAttribute("type", "1");
        } else if ("branch".equals(user.getDuty())) {
            model.addAttribute("type", "2");
        } else if ("teacher".equals(user.getDuty())) {
            model.addAttribute("type", "3");
        } else {
            model.addAttribute("type", "4");
        }
        return "base/user/addUser";
    }

    /**
     * QY 2018/9/4 23:49
     * 方法描述：跳转查看页面
     **/
    @RequestMapping(value = "/showSMasterPage", method = RequestMethod.GET)
    public String showSMasterPage(Principal principal,@RequestParam String menuId, @RequestParam String type,@RequestParam String userId, Model model, HttpServletRequest request) {
        model.addAttribute("userId", userId);
        model.addAttribute("menuId",menuId);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        model.addAttribute("menuSub", menuUtils.getMenuByRoleId(request, "21"));
        User userCurrent = userService.queryUserById(userId);
        if ("master".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "1");
        } else if ("branch".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "2");
        } else if ("teacher".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "3");
        } else {
            model.addAttribute("ctype", "4");
        }
        String uname = principal.getName();
        User user = mysqlUtil.getUserByLoginNameCommon(uname);
        model.addAttribute("stype", type);//当前点击的菜单类型
        if ("admin".equals(user.getDuty())) {
            model.addAttribute("type", "0");
        }else if ("master".equals(user.getDuty())) {
            model.addAttribute("type", "1");
        } else if ("branch".equals(user.getDuty())) {
            model.addAttribute("type", "2");
        } else if ("teacher".equals(user.getDuty())) {
            model.addAttribute("type", "3");
        } else {
            model.addAttribute("type", "4");
        }
        return "base/user/showUser";
    }

    /**
     * QY 2018/9/3 16:13
     * 方法描述：跳转到修改页面
     **/
    @RequestMapping(value = "/showUpdateMasterPage", method = RequestMethod.GET)
    public String showUpdateMasterPage(Principal principal,@RequestParam String menuId, @RequestParam String type, @RequestParam String userId, Model model, HttpServletRequest request) {
        model.addAttribute("userId", userId);
        model.addAttribute("menuId",menuId);
        model.addAttribute("backUrl",menuUtils.getMealUrlByParentId(menuId));
        model.addAttribute("menuSub", menuUtils.getMenuByRoleId(request, "22"));
        model.addAttribute("userId", userId);
        User userCurrent = userService.queryUserById(userId);
        if ("master".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "1");
        } else if ("branch".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "2");
        } else if ("teacher".equals(userCurrent.getDuty())) {
            model.addAttribute("ctype", "3");
        } else {
            model.addAttribute("ctype", "4");
        }
        String uname = principal.getName();
        User user = mysqlUtil.getUserByLoginNameCommon(uname);
        model.addAttribute("stype", type);//当前点击的菜单类型
        if ("admin".equals(user.getDuty())) {
            model.addAttribute("type", "0");
        }else if ("master".equals(user.getDuty())) {
            model.addAttribute("type", "1");
        } else if ("branch".equals(user.getDuty())) {
            model.addAttribute("type", "2");
        } else if ("teacher".equals(user.getDuty())) {
            model.addAttribute("type", "3");
        } else {
            model.addAttribute("type", "4");
        }
        return "base/user/updateUser";
    }
    /**
     * QY 2018/9/3 8:32
     * 方法描述：跳转添加用户组织页面
     **/
    @RequestMapping(value = "/showUserOrgPage", method = RequestMethod.GET)
    public String showUserOrgPage(@RequestParam String userId, Model model) {
        model.addAttribute("userId", userId);
        return "base/user/addUserOrg";
    }

    /**
     * QY 2018/9/4 23:49
     * 方法描述：跳转查看页面
     **/
    @RequestMapping(value = "/showUpdateUserOrgAccountPage", method = RequestMethod.GET)
    public String showUpdateUserOrgAccountPage(Principal principal, @RequestParam String orgId,@RequestParam String parentId,@RequestParam String type,@RequestParam String userId, Model model) {
        model.addAttribute("orgId", orgId);
        model.addAttribute("parentId", parentId);
        model.addAttribute("type", type);
        model.addAttribute("userId", userId);
        return "base/user/updateUserOrgAccount";
    }

    @RequestMapping(value = "/showUserOrgAccountPage", method = RequestMethod.GET)
    public String showUserOrgAccountPage(Principal principal, @RequestParam String orgId,@RequestParam String parentId, Model model) {
        model.addAttribute("orgId", orgId);
        model.addAttribute("parentId", parentId);
        return "base/user/showUserOrgAccountPage";
    }

    /**
     * QY 2018/9/3 10:16
     * 方法描述：查询所有用户
     **/
    @RequestMapping(value = "/queryAll", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO queryAll(Pageable pageable) {
        PageInfo <User> queryRoleList = userService.queryAll(pageable.getPageNumber(), pageable.getPageSize());

        JSONObject map = new JSONObject();
        map.put("total", queryRoleList.getTotal());
        map.put("rows", queryRoleList.getList());
        map.put("pageNumber", queryRoleList.getPageNum());
        map.put("pageSize", queryRoleList.getPageSize());
        ResultDTO result = ResultDTO.builder().data(map).build();
        return result;
    }

    /**
     * QY 2018/9/3 10:16
     * 方法描述：更改状态
     **/
    @RequestMapping(value = "/updateState", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO updateState(@RequestParam String state, @RequestParam String id) {
        return ResultDTO.builder()
                .data(userService.updateState(state, id))
                .build();
    }

    @RequestMapping(value = "/updateUserOrgAccountLessonAccount", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO updateUserOrgAccountLessonAccount(@RequestBody ReqTuple reqTuple) {
        Map<String,Object> map = reqTuple.getParmsMap();
        String orgId = (String)map.get("orgId");
        String parentId = (String)map.get("parentId");
        String lessonAccount = (String)map.get("lessonAccount");
        return ResultDTO.builder()
                .data(
                        userService.updateUserOrgAccountLessonAccount(orgId, parentId, lessonAccount)


                )
                .build();
    }

    /**
     * QY 2018/9/3 16:14
     * 方法描述：添加用户
     **/
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO addUser(@RequestBody ReqTuple reqTuple,HttpServletRequest request) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    HttpSession session = request.getSession();
                    User user=(User) session.getAttribute("currentUser");
                    if("student".equals(user.getDuty())){
                        t.setMessage("操作用户无职位过低无法进行该操作，请联系管理");
                        t.setIsSuccess(false);
                        t.setCode("201");
                    }else {
                        t.setData(userService.addUser(reqTuple.getParmsMap()));
                        t.setIsSuccess(true);
                    }
                },
                (e, t) -> {
                    e.printStackTrace();
                    log.info(e.getMessage());
                    t.setIsSuccess(false);
                    t.setMessage("新增用户失败");
                }
        );
    }

    /**
     * QY 2018/9/3 17:08
     * 方法描述：根据用户id查用户
     **/
    @RequestMapping(value = "/queryUserById", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO queryUserById(@RequestParam String userId) {
        return ResultDTO.builder()
                .data(userService.queryUserById(userId))
                .build();
    }

    /**
     * QY 2018/9/3 17:08
     * 方法描述：根据用户id查用户
     **/
    @RequestMapping(value = "/queryUserOrgAccountByOrgIdAndParentId", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO queryUserOrgAccountByOrgIdAndParentId(@RequestParam String orgId,@RequestParam String parentId) {
        return ResultDTO.builder()
                .data(userService.queryUserOrgAccountByOrgIdAndParentId(orgId,parentId))
                .build();
    }

    /**
     * QY 2018/9/3 17:08
     * 方法描述：删除成员
     **/
    @RequestMapping(value = "/delUser", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO delUser(@RequestParam String id) {
        return ResultDTO.builder()
                .data(userService.delUserById(id))
                .build();
    }

    /**
     * QY 2018/9/3 17:08
     * 方法描述：删除成员
     **/
    @RequestMapping(value = "/delUserOrgAccount", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO delUserOrgAccount(@RequestParam String id) {
        return ResultDTO.builder()
                .data(userService.delUserSubById(id))
                .build();
    }

    /**
     * QY 2018/9/3 17:10
     * 方法描述：修改成员
     **/
    @RequestMapping(value = "/updateUserByUserId", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO updateUserByUserId(@RequestBody ReqTuple reqTuple,HttpServletRequest request) {
        Map<String,Object>parms=reqTuple.getParmsMap();
        HttpSession session = request.getSession();
        User user=(User) session.getAttribute("currentUser");
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    if("student".equals(user.getDuty())){
                        t.setMessage("操作用户无职位过低无法进行该操作，请联系管理");
                        t.setIsSuccess(false);
                        t.setCode("201");
                    }else {
                        //修改用户基本信息
                        userService.updateUserByUserId(parms);
//                        //初始化日志信息
//                        UserCountLog userCountLog=UserCountLog.builder()
//                                .createTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
//                                .newNum(Integer.parseInt(parms.get("purchaseNum").toString()))
////                                .originalNum()).getLessonAccount())
//                                .userId(user.getId())
//                                .userLoginName(user.getLoginName())
//                                .build();
//                        //如果如果带了统计表ID修改操作   否则新增操作
//                        if(!"".equals(parms.get("userCountId")) && null != parms.get("userCountId")){
//                            UserOrgAccount userOrgAccount=userService.queryOrderById(String.valueOf(parms.get("userCountId")));
//                            userCountLog.setResult("修改操作成功");
//                            userCountLog.setNewNum(Integer.parseInt(parms.get("purchaseNum").toString()));
//                            userCountLog.setOriginalNum(userOrgAccount.getLessonAccount());
//                            userCountLog.setUserCountId(userService.updateUserOrgAccountLessonAccount(userOrgAccount.getOrgId(),userOrgAccount.getUserId(),parms.get("purchaseNum").toString()));
//                        }else {
//                            userCountLog.setResult("新增操作成功");
//                            userCountLog.setNewNum(Integer.parseInt(parms.get("purchaseNum").toString()));
//                            userCountLog.setOriginalNum(0);
//                            userCountLog.setUserCountId( userService.updateUserOrgAccountLessonAccount(parms.get("orgId").toString(),parms.get("id").toString(),parms.get("purchaseNum").toString()));
//                        }
//                        userService.insertUserCountLog(userCountLog);
                        t.setIsSuccess(true);
                    }
                },
                (e, t) -> {
                    e.printStackTrace();
//                    userCountLog.setResult("修改失败");
//                    if(StringUtils.isNotEmpty(String.valueOf(parms.get("userCountId")))){
//                        userService.insertUserCountLog(userCountLog);
//                    }
                    t.setIsSuccess(false);
                    t.setMessage("修改用户");
                }
        );
    }

    /**
     * QY 2018/9/4 10:37
     * 方法描述：根据用户名称查询用户详情
     **/
    @RequestMapping(value = "/queryUserByUserName", method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO queryUserByUserName(Principal principal,Pageable pageable, @RequestParam String sel,@RequestParam String type) {
        String uname = principal.getName();
        User user = mysqlUtil.getUserByLoginNameCommon(uname);
        String duty = user.getDuty();
        String orgId = user.getOrgId();
        PageInfo <User> res = userService.queryUserByUserName(pageable.getPageNumber(), pageable.getPageSize(), sel,duty,orgId,type);
        JSONObject map = new JSONObject();
        map.put("total", res.getTotal());
        map.put("rows", res.getList());
        return ResultDTO.builder()
                .data(map)
                .build();
    }

    /**
     * QY 2018/9/4 13:56
     * 方法描述：添加用户与组织关系
     **/
//    @RequestMapping(value = "/addUserOrgList",method = RequestMethod.POST)
//    @ResponseBody
//    public ResultDTO addUserOrgList(@RequestBody ReqTuple reqTuple){
//        return  ResultDTO.builder()
//                .data(userService.addUserOrgList(reqTuple.getParmsList(),reqTuple.userId))
//                .build();
//    }
    @RequestMapping(value = "/queryUserOrgByUserId", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO queryUserOrgByUserId(@RequestParam String userId) {
        List <OrgZTreeNode> zTreeNodes = new ArrayList <>();
        List <Org> queryOrg = orgService.queryOrg();
        List <String> queryUserOrg = new ArrayList <>();
        if (!userId.equals("") || !userId.equals(null)) {
            queryUserOrg = userService.queryUserOrgByUserId(userId);
        }
        for (Org orgNode : queryOrg) {
            OrgZTreeNode orgZTreeNode = new OrgZTreeNode();
            orgZTreeNode.setId(orgNode.getId());
            orgZTreeNode.setPid(orgNode.getParentId());
            orgZTreeNode.setName(orgNode.getOrgName());
            if (queryUserOrg.size() > 0) {
                for (String orgId : queryUserOrg) {
                    if (orgId.equals(orgNode.getId())) {
                        orgZTreeNode.setChecked(true);
                    }
                }
            }
            zTreeNodes.add(orgZTreeNode);
        }
        return ResultDTO.builder()
                .data(zTreeNodes)
                .build();
    }

    @RequestMapping(value = "/queryUserByLoginName", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO queryUserByLoginName(@RequestParam String userName) {
        return ResultDTO.builder()
                .data(userService.queryUserByLoginName(userName))
                .build();
    }

    @PostMapping("/addUserAttach")
    @ResponseBody
    public ResultDTO addUserAttach(@RequestParam("file") MultipartFile file, @RequestParam("id") String id) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    //入库路径
                    String realPath = uploadUtiles.getCurrentAddress(imgUrl);
                    //上传路径
                    String savePath = uploadUtiles.getLocationAddress(imgUrl);
                    String fileName = uploadUtiles.getUpImg(savePath, file);
                    if (null != fileName && !"".equals(fileName)) {
                        UserAttach userAttach = new UserAttach();
                        userAttach.setUserId(Integer.parseInt(id));
                        userAttach.setAttachmentUrl(realPath + fileName);
                        userService.addUserAttach(userAttach);
                        t.setIsSuccess(true);
                        t.setData(userAttach.getAttachmentUrl());
                    } else {
                        log.info("图片上传失败");
                        t.setIsSuccess(false);
                        t.setMessage("图片上传失败");
                    }
                },
                (e, t) -> {
                    e.printStackTrace();
                    log.info(e.getMessage());
                    t.setIsSuccess(false);
                    t.setMessage("新增失败");
                }
        );
    }

    @GetMapping("/queryUserDescAllByUserId")
    @ResponseBody
    public ResultDTO queryUserDescAllByUserId(String userId) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    t.setData(userService.queryUserDescAllByUserId(userId));
                    t.setIsSuccess(true);
                },
                (e, t) -> {
                    e.printStackTrace();
                    log.info(e.getMessage());
                    t.setIsSuccess(false);
                    t.setMessage("获取详情失败");
                }
        );
    }

    @PostMapping("/updateUserDesc")
    @ResponseBody
    public ResultDTO updateUserDesc(@RequestBody ReqTuple reqTuple) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    userService.updateUserDesc(reqTuple.getUser());
                    t.setIsSuccess(true);
                    t.setMessage("教师风采添加成功");
                }, (e, t) -> {
                    e.printStackTrace();
                    log.info(e.getMessage());
                    t.setIsSuccess(false);
                    t.setMessage("修改教师风采失败");
                }
        );
    }

    @PostMapping("/delUserAttach")
    @ResponseBody
    public ResultDTO delUserAttach(@RequestParam("id") String id, @RequestParam("imgUrl") String imgUrl) {
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t -> {
                    clearTempImg.clearImgs(imgUrl);
                    userService.delUserAttach(id, imgUrl);
                    t.setIsSuccess(true);
                    t.setMessage("教师风采删除成功");
                }, (e, t) -> {
                    e.printStackTrace();
                    log.info(e.getMessage());
                    t.setIsSuccess(false);
                    t.setMessage("删除失败");
                }
        );
    }

    @RequestMapping(value = "/queryUserDutyByLoginName", method = RequestMethod.POST)
    @ResponseBody
    public ResultDTO queryUserDutyByLoginName(Principal principal,String userName) {
        User user = mysqlUtil.getUserByLoginNameCommon(userName);
        String duty = user.getDuty();
        JSONObject map = new JSONObject();
        map.put("duty", duty);
        return ResultDTO.builder().data(map).build();
    }

    @RequestMapping(value = "/queryUserSubById",method = RequestMethod.GET)
    @ResponseBody
    public ResultDTO queryUserSubById(Principal principal,Pageable pageable, String parm){
        Map<String,Object> data = new HashMap<>();
        return iComboExecptionForTFunc.executeFlow(
            ResultDTO.builder().build(),
            t->{
                String uname = principal.getName();
                User user = userMapper.queryRoleUserByLoginName(uname);
                String orgId = orgService.queryOrgIdByUserId(String.valueOf(user.getId()));

                String dutyFlag = "";
                //4是老师
                if("master".equals(user.getDuty())){
                    dutyFlag="1";
                }
                if("branch".equals(user.getDuty())){
                    dutyFlag="2";
                }
                if("teacher".equals(user.getDuty())){
                    dutyFlag="3";
                }
                if("admin".equals(user.getDuty())){
                    dutyFlag="0";
                }

                PageInfo pageInfo=userService.queryUserSubById(parm,pageable, orgId, String.valueOf(user.getId()),dutyFlag);

                data.put("rows",pageInfo.getList());
                data.put("total",pageInfo.getTotal());
                t.setData(data);
                t.setIsSuccess(true);
                t.setMessage("查询子账号成功");
            },(e,t) ->{
                    e.printStackTrace();
                    log.info(e.getMessage());
                    t.setIsSuccess(false);
                    t.setMessage("查询失败");
                }
        );
    }

    @GetMapping("/queryUserCountByUserId/{userCount}/{purchaseNum}/{userId}")
    String queryUserCountByUserId(@PathVariable String userCount,@PathVariable String purchaseNum,@PathVariable String userId, Model model){
        model.addAttribute("userCountId",userCount);
        model.addAttribute("lessonAccount",purchaseNum);
        model.addAttribute("userId",userId);
        return "base/user/updateACount";
    }

    @GetMapping("/getUserACountById/{userCountId}")
    @ResponseBody
    ResultDTO getUserACountById(@PathVariable String userCountId,Pageable pageable){
        return iComboExecptionForTFunc.executeFlow(
               ResultDTO.builder().build(),
                t->{
                    Map<String,Object> data = new HashMap<>();
                    PageInfo pageInfo=userService.getUserACountById(pageable,userCountId);
                    data.put("rows",pageInfo.getList());
                    data.put("total",pageInfo.getTotal());
                    t.setData(data);
                    t.setIsSuccess(true);
                    t.setMessage("查询成功");
                },(e,t)->{
                    e.printStackTrace();
                    log.info(e.getMessage());
                    t.setIsSuccess(false);
                    t.setMessage("查询失败");
                }
        );
    }

    @PostMapping("/updateUserAccount")
    @ResponseBody
    ResultDTO updateUserAccount(@RequestBody ReqTuple reqTuple){
        return iComboExecptionForTFunc.executeFlow(
                ResultDTO.builder().build(),
                t->{
                    Map<String,Object>map=reqTuple.getParmsMap();
                    UserOrgAccount userOrgAccount=userService.queryUserOrgAccount(map.get("userId").toString());
                    User user=userService.queryUserById(map.get("userId").toString());
                    String result="";
                    int originalNum=0;
                    if(null !=userOrgAccount){
                         int count= userService.updateLessonAccountById(
                                 UserOrgAccount.builder()
                                     .id(userOrgAccount.getId())
                                     .userId(map.get("userId").toString())
                                     .lessonAccount(Integer.parseInt(map.get("lessonAccount").toString()))
                                     .updateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                                     .build());
                        result=count>0?"修改成功":"修改失败";
                        originalNum=userOrgAccount.getLessonAccount();
                    }else {
                        userOrgAccount.setUserId(map.get("userId").toString());
                        userOrgAccount.setOrgId(user.getOrgId());
                        userOrgAccount.setLessonAccount(Integer.parseInt(map.get("lessonAccount").toString()));
                        int count= userService.insertLessonAccount(userOrgAccount);
                        result=count>0?"新增成功":"新增失败";
                        originalNum=0;
                    }
                    int num= userService.insertUserCountLog(
                            UserCountLog.builder()
                                    .userCountId(userOrgAccount.getId())
                                    .userId(Integer.parseInt(map.get("userId").toString()))
                                    .result(result)
                                    .userLoginName(user.getLoginName())
                                    .originalNum(originalNum)
                                    .newNum(Integer.parseInt(map.get("lessonAccount").toString()))
                                    .createTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                                    .remarks(map.get("remarks").toString())
                                    .build());
                    t.setIsSuccess(num>0 ? true : false);
                    t.setMessage(num>0 ? "修改成功" : "修改失败");
                    t.setData(userOrgAccount.getId());
                },(e,t)->{
                    e.printStackTrace();
                    log.info(e.getMessage());
                    t.setIsSuccess(false);
                    t.setMessage("修改失败");
                }
        );

    }
}
